<template>
  <div>
    <el-form :model="marketForm" @submit.native.prevent="onSubmit('marketForm',$event)" :rules="rules" ref="marketForm" label-width="100px" style="width:460px">
      <el-form-item label="市场名称:" prop="marketName">
        <el-input v-model="marketForm.marketName" :disabled="status==1" clearable placeholder="请输入市场名称"></el-input>
      </el-form-item>
      <el-form-item label="市场简称:" prop="marketShortName">
        <el-input v-model="marketForm.marketShortName" :disabled="status==1" clearable placeholder="请输入市场简称"></el-input>
      </el-form-item>
      <el-form-item label="市场电话" prop="marketMobile">
        <el-input v-model="marketForm.marketMobile" :disabled="status==1" clearable placeholder="请输入市场电话"></el-input>
      </el-form-item>
      <el-form-item label="市场地址:" prop="marketAddress">
        <el-input v-model="marketForm.marketAddress" :disabled="status==1" clearable placeholder="请输入市场地址"></el-input>
      </el-form-item>
      <el-form-item label="经纬度:"  prop="marketLat">
        <el-col :span="11">
          <el-form-item prop="marketLat">
            <el-input v-model="marketForm.marketLat" placeholder="经度" :disabled="status==1"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"><span>&nbsp;</span></el-col>
        <el-col :span="11">
          <el-form-item prop="marketLng">
            <el-input v-model="marketForm.marketLng" placeholder="纬度" :disabled="status==1"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="归属地区:" prop="provinceId">
        <el-col :span="11">
          <el-form-item prop="provinceId">
            <el-select  v-model="marketForm.provinceId" placeholder="请选择" :disabled="status==1" @change="getCity()">
              <el-option
                v-for="item in res.provinceOptions"
                :key="item.provinceId"
                :label="item.provinceName"
                :value="item.provinceId" >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2"><span>&nbsp;</span></el-col>
        <el-col :span="11">
          <el-form-item prop="cityId">
            <el-select v-model="marketForm.cityId" placeholder="请选择" :disabled="status==1">
              <el-option
                v-for="item in  res.cityOptions"
                :key="item.cityId"
                :label="item.cityName"
                :value="item.cityId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="上传LOGO">
        <el-upload
          :disabled="status==1"
          name="file"
          action="uploadUrl"
          list-type="picture-card"
          accept="image/*"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :on-change="getFile"
          :on-remove="handleRemove"
          :auto-upload="false"
          :file-list="fileList"
          :show-file-list="false"
          >
          <i class="el-icon-plus"></i>
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
        </el-upload>
        <!--<el-dialog :visible.sync="dialogVisible">-->
          <!--<img width="100%" :src="dialogImageUrl" alt="">-->
        <!--</el-dialog>-->
      </el-form-item>
      <el-form-item>
        <button type="submit" class="el-button el-button--primary" v-show="status!=1">{{buttonName}}</button>
        <el-button @click="turnToList">返回列表</el-button>
        <el-button @click="resetForm('marketForm')" v-if="!marketId">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        imageUrl:"",
        uploadUrl: '#',
        buttonName: '',
        dialogImageUrl: '',
        dialogVisible: false,
        imgUrl:imageUrl,
        fileList: [],
        marketId: this.$route.params.id,
        marketForm:{
          marketName: '',
          marketShortName: '',
          marketMobile: '',
          marketAddress: '',
          provinceId: '',
          cityId: '',
          cityName: '',
          provinceName: '',
          marketParentId: 1,
          marketLat: '',
          marketLng:'',
        },
        res: {
          provinceOptions: [],
          cityOptions: [],
          params: {}
        },
        rules: {
          marketName: [
            { required: true, message: '请输入市场名称', trigger: 'blur' },
            { max: 20, message: '最多20个字符', trigger: 'blur' }
          ],
          marketShortName: [
            { required: true, message: '请输入市场简称', trigger: 'change' }
          ],
          marketMobile: [
            { required: true, message: '请输入市场电话', trigger: 'blur' },
            { min: 11 , max: 11, message: '必须11位', trigger: 'blur' }
          ],
          marketAddress: [
            { required: true, message: '请输入市场地址', trigger: 'blur' }
          ],
          provinceId: [
            { required: true, message: '请选择省', trigger: 'blur' }
          ],
          cityId: [
            { required: true, message: '请选择市区', trigger: 'blur' }
          ]
        },
        isDisable:false
      };
    },
    computed:{
      status(){
        return this.$route.query.status;
      }
    },
    watch:{
      'marketForm.provinceId' () {
        this.$nextTick().then(() => {
          this.res.cityOptions = [];
          this.res.provinceId = this.marketForm.provinceId;
          this.cityOptions = [];
          this.$store.commit('getCityOptions', this.res);
        })
      },
      '$route'(){
        if (!this.$route.params.id){
          this.marketId = '';
          this.marketForm = {
            marketName: '',
            marketShortName: '',
            marketMobile: '',
            marketAddress: '',
            provinceId: '',
            cityId: '',
            cityName: '',
            provinceName: '',
            marketParentId: 1,
            marketLat: '',
            marketLng:'',
          };
          this.imageUrl = '';
          this.buttonName = '立即创建'
        }
      }
    },
    created(){
      this.$store.commit('getProvinceOptions',this.res);
      this.$store.commit('getCityOptions', this.res);
    },
    methods: {
      getCity(){
        this.$axios.get(this.$api.city,{params:{provinceId:this.marketForm.provinceId}}).then((res)=>{
          if(res){
            this.cityOptions = res.data.result;
            setTimeout(()=>{
              this.marketForm.cityId = res.data.result[0].cityId;
            },500)
          }
        })
      },
      getData(){
        this.$axios.get(this.$api.getMarketList,
          { params: {marketId: this.marketId}}).then((res) => {
          this.marketForm = res.data.result[0]
          delete  this.marketForm.marketCreateTime;
          delete  this.marketForm.marketUpdateTime;
          if (this.marketForm.marketLogo) {
            let url = this.imgUrl + this.marketForm.marketLogo;
            this.imageUrl = url;
            this.fileList = [{url:url}]
          }
        })
      },
      handleRemove(file, fileList) {

      },
      getFile(file,fileList){
        if(fileList.length>1){
          fileList.splice(0,1)
        }
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 /1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      handlePictureCardPreview(file) {
        // this.dialogImageUrl = file.url;
        // this.dialogVisible = true;
      },
      turnToList(){
        this.$router.push('/market/marketList')
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.fileList=[];
        this.imageUrl = ''
      },
      onSubmit(marketForm,$event) {
        var requestParam = this.marketForm;
        var formData = new FormData($event.target);
        this.$refs[marketForm].validate((valid) => {
          if (valid) {
            for(let i in requestParam){
              formData.append(i,requestParam[i])
            }
            this.$axios({
              method: 'post',
              url: this.$api.updateMarket,
              data: formData
            }).then((res) => {
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              if (res.data.code == 1){
                this.$router.push('/market/marketList')
              }else{
                this.$router.push('/market/marketForm')
              }
            })
          } else {
            this.$message({
              type:'warning',
              message:'提交失败'
            });
            return false;
          }
        });

      }
    },
    activated() {
      this.marketId = this.$route.params.id;
      if (this.$route.params.id != null ){
        this.getData();
        this.buttonName = '立即更新'
      }else{
        this.marketId = '';
        this.resetForm('marketForm') ;
        this.buttonName = '立即创建'
      }
    },
    deactivated() {

    }
  }
</script>
<style scoped>
  .avatar {
    position: absolute;
    top: 0;
    left: 0;
    width: 148px;
    height: 148px;
    display: block;
  }
</style>
